package me.jiatao.shirostudy.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

@RestController
public class LoginController {

    //退出的时候是get请求，主要是用于退出
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public ModelAndView login() {
        return new ModelAndView("loginIndex.html");
    }

    @RequestMapping(value = "/userLogin", method = RequestMethod.POST)
    public ModelAndView login(@RequestParam("name") String username, @RequestParam("pwd") String password) {
        //添加用户认证信息
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(
                username,
                password);
        //是否记住密码
        //usernamePasswordToken.setRememberMe(true);
        //进行验证，这里可以捕获异常，然后返回对应信息
        //传入CustomShiroRealm
        try {
            subject.login(usernamePasswordToken);
            //subject.hasRole();
            subject.isAuthenticated();
        } catch (LockedAccountException ex) {
            return new ModelAndView("loginIndex.html");
        } catch (AuthenticationException ex) {
            return new ModelAndView("loginIndex.html");
        }
        return new ModelAndView("redirect:/list");
    }

    @GetMapping(value = "/list")
    public ModelAndView list() {
        return new ModelAndView("list.html");
    }

    //登出
    @GetMapping(value = "/logout")
    public String logout() {
        return "logout";
    }

    //错误页面展示
    @GetMapping(value = "/unauthorized")
    public String unauthorized() {
        return "授权失败";
    }


    @GetMapping(value = "/adminPage")
    public ModelAndView adminPage(){
        return new ModelAndView("admin.html");
    }
    @GetMapping(value = "/userPage")
    public ModelAndView userPage(){
        return new ModelAndView("user.html");
    }

//    //数据初始化
//    @RequestMapping(value = "/addUser")
//    public String addUser(@RequestBody Map<String, Object> map) {
//        return "addUser is ok! \n";
//    }
//
//    //角色初始化
//    @RequestMapping(value = "/addRole")
//    public String addRole(@RequestBody Map<String, Object> map) {
//
//        return "addRole is ok! \n";
//    }
//
//    //注解的使用
//    @RequiresRoles("admin")
//    @RequiresPermissions("create")
//    @RequestMapping(value = "/create")
//    public String create() {
//        return "Create success!";
//    }
}